import {
    getWorkBench,
    getAccountExpireNotify,
    getDetectRecord,
    dybbAd,
    getapplylistallapi
} from '../../api/app.js'
import {
    goApp
} from '../../utils/util.js'
import user from '../../utils/user.js'
import global from '../../utils/global'
import dayjs from 'dayjs'
const app = getApp()
Page({
    data: {
        isShow: false,
        data: [{
            'id': 10,
            'menuName': '无卡发薪',
            'typeId': 0,
            'typeName': '发薪',
            'orderNum': 0,
            'path': 'tab::/pages/index/index',
            'component': '',
            'visible': '0',
            'isDelete': '0',
            'icon': 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/955b72b0-b34d-40bf-8198-4480ae69d073.jpg',
            'createUserId': '',
            'createTime': null,
            'updateUserId': '',
            'updateTime': null,
            'remark': '',
            'params': {}
        },
        {
            'id': 17,
            'menuName': '长期保',
            'typeId': 1,
            'typeName': '风险管控',
            'orderNum': 1,
            'path': 'applet::/packageLongInsure/pages/index/index',
            'component': null,
            'visible': '0',
            'isDelete': '0',
            'icon': 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/32c62d5d-c988-483e-b7b1-c08723f46e22.jpg',
            'createUserId': '',
            'createTime': null,
            'updateUserId': '',
            'updateTime': null,
            'remark': '',
            'params': {}
        },
        {
            'id': 14,
            'menuName': '日日保',
            'typeId': 1,
            'typeName': '风险管控',
            'orderNum': 2,
            'path': 'applet::/packageInsurance/pages/insurance/insurance',
            'component': null,
            'visible': '0',
            'isDelete': '0',
            'icon': 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/46b96900-1825-48d9-a4dc-ef9e39e6a347.jpg',
            'createUserId': '',
            'createTime': null,
            'updateUserId': '',
            'updateTime': null,
            'remark': '',
            'params': {}
        },
        {
            'id': 2,
            'menuName': '企业管理',
            'typeId': 2,
            'typeName': '管理',
            'orderNum': 2,
            'path': 'applet::/pages/enterprise/enterprise',
            'component': null,
            'visible': '0',
            'isDelete': '0',
            'icon': 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/f5d6370d-3f9d-46ff-9e64-3ff9e85ca038.jpg',
            'createUserId': '',
            'createTime': null,
            'updateUserId': '',
            'updateTime': null,
            'remark': '',
            'params': {}
        },
        {
            component: null,
            createTime: null,
            createUserId: '1',
            icon: 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/95a7c746-9ffa-4ac1-8387-ade9d54b9006.jpg',
            id: 21,
            isDelete: '0',
            menuName: '审批管理',
            orderNum: 8,
            params: {},
            path: 'applet::/packagePay/pages/examine/index/index',
            remark: '',
            typeId: 2,
            typeName: '管理',
            updateTime: null,
            updateUserId: '',
            visible: '0',
        },
        {
            component: null,
            createTime: null,
            createUserId: '1',
            icon: 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/img/3b630264-3239-4e49-91a1-4b22843e2649.jpg',
            id: 22,
            isDelete: '0',
            menuName: '发票管理',
            orderNum: 9,
            params: {},
            path: 'applet::/packagePay/pages/invoice/invoice',
            remark: '',
            typeId: 2,
            typeName: '管理',
            updateTime: null,
            updateUserId: '',
            visible: '0',
        }
        ],
        companyName: '',
        top: app.globalData.menuTop,
        autoplay: false,
        isPopupPay: false,
        workBenchMenu: {
            '发薪': [{
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }],
            '风险管控': [{
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }],
            '管理': [{
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }, {
                icon: null
            }]
        },
        isArticle: false,
        noBuyUser: false,
        ispopupRemind: false,
        isWorkActivity: true,
        isLogon: true,
        isFatherLogon: false,
        learnadvanceflag: false
    },
    todrag() {
        wx.navigateTo({
            url: '/pages/drag/drag',
        })
    },
    closetolearn() {
        this.setData({
            learnadvanceflag: false
        })
        wx.navigateTo({
            url: '/packageAdvance/pages/advanceIndex/advanceIndex',
        })
    },
    close() {
        wx.setStorageSync('haslearnadvance', 'true')
        this.setData({
            learnadvanceflag: false
        })
    },
    toadvancelearn() {
        wx.navigateTo({
            url: '/packageAdvance/pages/learnadvance/learnadvance',
        })
    },
    // ndzdbg() {
    //     dybbAd({
    //         isShare: 0,
    //         isExposure: 1,
    //         type: 1,
    //     }).then((res) => {
    //         console.log(res, 'fgasgyfjiusagygyasu')
    //     })
    // },
    changeswiper(e) {
        let i = e.detail.current
        console.log(i, 'gsatuygyhuads')
        // if (i === 0) {
        //     this.ndzdbg()
        // }
        // if (i === 2) {
        //     this.dybbAdfn(0, 1, 0)
        // }
    },
    tondzd() {
        if (wx.getStorageSync('hasRead2023ndzd')) {
            wx.navigateTo({
                url: '/packageActivitys/inviteFriends/inviteFriends',
            })
        } else {
            wx.navigateTo({
                url: '/packageActivitys/annualSpendingReport/annualSpendingReport',
            })
        }
        console.log('去年度账单页面')
    },
    onHide() {
        this.setData({
            autoplay: false
        })
    },
    tochangeCompany() {
        wx.navigateTo({
            url: '/pages/changeCompany/changeCompany',
        })
    },
    onShow() {
        const accountInfo = wx.getAccountInfoSync()
        let flag = accountInfo.miniProgram.envVersion === 'release'
        this.setData({
            isShow: flag
        })
        if (wx.getStorageSync('haslearnadvance')) {
            this.setData({
                learnadvanceflag: false
            })
        } else {
            this.setData({
                learnadvanceflag: true
            })
        }
        user.waitLogin().then(() => {
            // this.dybbAdfn(0, 1, 0)
            this.setData({
                autoplay: true,
                noBuyUser: !user.auditStatus,
                isWorkActivity: user.isWorkActivity,
                isFatherLogon: global.token ? true : false,
                companyName: user.companyName,
            })
            // 获取菜单列表
            getWorkBench().then(res => {
                getapplylistallapi({
                    searchText: '',
                    queryApplyDate: dayjs().format('YYYY-MM-DD'),
                    applyStatus: 0
                }).then((resc) => {
                    console.log((resc), 111111111)
                    let arr = this.flat(resc)
                    let len = arr.length
                    res['发薪'].forEach((ele, i) => {
                        if (ele.menuName == '预支工资') {
                            ele.remark = len === 0 ? '' : len + ''
                        }
                    })
                    if (res['自定义'].length == 0) {
                        console.log(this.data.data)
                        this.data.data.forEach((ele, i) => {
                            res['自定义'].push(ele)
                        })
                    } else if (res['自定义'][0].id === -1) {
                        res['自定义'] = []
                    }
                    res['自定义'].push({
                        'id': 999999999999,
                        'menuName': '添加常用',
                        'typeId': 999999999999,
                        'typeName': '管理',
                        'orderNum': 999999999,
                        'path': 'applet::/pages/drag/drag',
                        'component': null,
                        'visible': '0',
                        'isDelete': '0',
                        'icon': 'https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManagercf8a99bb-8db9-46cb-a99d-168e3425e1ba.png',
                        'createUserId': '',
                        'createTime': null,
                        'updateUserId': '',
                        'updateTime': null,
                        'remark': '',
                        'params': {}
                    }, )
                    let arrc = Object.entries(res)
                    let lastItem = arrc.pop()
                    arrc.unshift(lastItem)
                    let newObj = Object.fromEntries(arrc)
                    this.setData({
                        workBenchMenu: newObj
                    })
                    console.log(newObj, 'res')
                })
            })
        }).catch(() => {
            this.setData({
                isFatherLogon: global.token ? true : false
            })
        })
        this.getTabBar().setData({
            selected: 1
        })
    },
    flat(arr) {
        const result = []
        const stack = [].concat(arr) // 将数组元素拷贝至栈，直接赋值会改变原数组
        // 如果栈不为空，则循环遍历
        while (stack.length !== 0) {
            const val = stack.pop()
            if (Array.isArray(val)) {
                stack.push(...val) // 如果是数组再次入栈，并且展开了一层
            } else {
                result.unshift(val) // 如果不是数组就将其取出来放入结果数组中
            }
        }
        return result
    },
    onLoad() {

    },
    //
    // 跳转方法
    async goApp(event) {
        const {
            path,
            menuname
        } = event.currentTarget.dataset
        if (!user.isOpenPaySalary && (path == 'applet::/packageRecruit/pages/work-job/work-job' || path == 'applet::/packageOther/pages/black-list/black-list')) {
            this.setData({
                isPopupPay: true
            })
            return
        }
        const result = await getAccountExpireNotify()
        this.setData({
            expirationTime: result
        })
        if ((result.status === 3) && (path == 'applet::/packageRecruit/pages/work-job/work-job' || path == 'applet::/packageOther/pages/black-list/black-list')) {
            this.setData({
                ispopupRemind: true
            })
            return
        } else {
            this.expireCancel()
        }
        if (path == 'applet::/packageMicroInsurance/pages/insurance/insurance') {
            const result = await getDetectRecord({
                type: 4
            })
            console.log(result)
            if (result == undefined) {
                wx.navigateTo({
                    url: '/packageMicroInsurance/pages/application-state/application-state?state=0&name=您暂未开通 微信支付商户号&tips=请联系商务开通后申请',
                })
                return
            } else if (result.status == 3) {
                wx.navigateTo({
                    url: '/packageMicroInsurance/pages/application-state/application-state?state=1&name=该申请通过后会及时通知超级管理员&title=提交成功！&tips=请关注微信通知',
                })
                return
            } else if (result.status == 5) {
                wx.navigateTo({
                    url: '/packageMicroInsurance/pages/application-state/application-state?state=2&name=点击返回后，请重新申请开通团意日保&title=审核失败！',
                })
                return
            } else if (result.status == 2) {
                wx.navigateTo({
                    url: '/packageMicroInsurance/pages/application/application',
                })
                return
            }
        }
        goApp(event.currentTarget.dataset.path, 'navigateTo', event.currentTarget.dataset.status)
        // 增加埋点，统计工作台的点击数
        wx.reportEvent('workbench_type', {
            'workbench_item_name': menuname
        })
    },
    // 忽略发薪
    expireCancel() {
        this.setData({
            ispopupRemind: false
        })
    },
    // 跳转到活动界面
    goExtension() {
        wx.navigateTo({
            url: '/packageActivity/pages/activity/activity',
        })
    },
    // 跳转到公众号文章。
    goArticle() {
        goApp('https://mp.weixin.qq.com/s/JWS1z9DzhgaVjexpioCnxw')
        // this.setData({
        //     isArticle:true
        // })
    },
    // dybbAdfn(isClick, isExposure, isPhone) {
    //     dybbAd({
    //         isClick: isClick,
    //         isExposure: isExposure,
    //         isPhone: isPhone,
    //         companyName: user.companyName,
    //         phone: user.phoneNum,
    //         type: 0
    //     }, {
    //         isLoading: false
    //     }).then((res) => {
    //         console.log(res, 'fgasgyfjiusagygyasu')
    //     })
    // },
    todybb() {
        this.dybbAdfn(1, 0, 0)
        wx.navigateTo({
            url: '/packageAd/pages/dybb/dybb',
        })
        wx.setStorageSync('hascolsedybbflag', true)
    },
    // 跳转到活动界面
    onActivity() {
        wx.navigateTo({
            url: '/packageActivity/pages/activity/activity'
        })
    },
    // 关闭活动页面
    onCloseActivity() {
        this.setData({
            isWorkActivity: false
        })
        user.isWorkActivity = false
    },
    onClose() {
        this.setData({
            isPopupPay: false
        })
    },
    onFloor() {
        console.log('回调点击出现函数')
        this.setData({
            isLogon: false
        })
    },
    onLogonCancel() {
        console.log('点击取消的回调')
        this.setData({
            isLogon: true
        })
    },
    // toStudy() {
    //     dybbAd({
    //         isClick: 1,
    //         type: 2,
    //     }).then((res) => {
    //         wx.navigateTo({
    //             url: '/packageAd/pages/studyJapan/studyJapan'
    //         })
    //     })
    // },
    // 去垫资解释页
    onGoAdvance() {
        console.log('点击了')
        wx.navigateTo({
            url: '/packageActivity/pages/advance-payment/advance-payment',
        })
    }
})